//
//  DBUtils.swift
//  ddx0513
//
//  Created by ejian  on 15/6/23.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import Foundation

class DBUtils {
    struct varNames {
        static let loginName = "login_name"
        
        static let password = "password"
        
        static let token = "token"
        
        static let userId = "user_id"
        
        static var loginStatus = "login_status"
        
        static let nickName = "nick_name"
        
        static let imgURL = "imgurl"
        
        static let pushAlias = "push_alias"
        
        static let pushTag = "push_tag"
        
        static let imUsername = "im_username"
        
        static let imPassword = "im_password"
        
        static let vipType = "vip_type"
        
        static let vipBegin = "vip_begin"
        
        static let vipExpire = "vip_expire"
        
        static let sortItem = "sort_item"
        
        static let chapterOrsection = "chapterOr_section"
        
        static let thisPage = "this_page"
        
        static let isCellularNet = "is_cellular_net"
        
    }
    
   struct mem {
        static var loginName = ""
        
        static var password = ""
        
        static var token = ""
        
        static var userId = 0
        
        static var loginStatus = false
        
        static var nickName = ""
        
        static var imgURL = ""
        
        static var pushAlias = ""
        
        static var pushTag = ""
        
        static var imUsername = ""
        
        static var imPassword = ""
        
        static var vipType = ""
        
        static var vipBegin: Int64 = 0
        
        static var vipExpire: Int64 = 0
        
        static var sortItem = 100
        
        static let imageCache = NSCache()
        
        static let vReadToken = "PiimIluziX-VfpGqDp6lP-btXBIGFhdO"
        
        static let vWriteToken = "TcCv0mQSwDQcyhm-920M7mXV0Q0h08uG"
        
        static let vSecretKey = "bQWvkOddnK"
        
        static let vUserId = "64770006a1"
        
        static var chapterOrsection = true
        
        static var thisPage = 1
    
        static var isCellularNet = false
    
//        static var isFullScreen = false
    }
    
    //退出登录
    class func logout() {
        mem.loginName = ""
        
        mem.password = ""
        
        mem.token = ""
        
        mem.userId = 0
        
        mem.loginStatus = false
        
        mem.nickName = ""
        
        mem.imgURL = ""
        
        mem.pushAlias = ""
        
        mem.pushTag = ""
        
        mem.imUsername = ""
        
        mem.imPassword = ""
        
        mem.vipType = ""
        
        mem.vipBegin = 0
        
        mem.vipExpire = 0
        
        mem.isCellularNet = false
    }
    
    //从内存中获取图片
    class func getImage(imageURL: String, successHandler:(String, UIImage) -> Void) {
        if (imageURL == "") {
            return
        }
        
        if let img = mem.imageCache.objectForKey(imageURL) as? UIImage {
            successHandler(imageURL, img)
        } else {
            request(Method.GET, imageURL).validate(contentType: ["image/*"]).response({ (_request, _response, image, error) -> Void in
                if (error == nil && image != nil) {
                    let img = UIImage(data: image as! NSData)
                    mem.imageCache.setObject(img!, forKey: imageURL)
                    successHandler(imageURL, img!)
                }
            })
        }
    }
    
    //在内存中保存图片
    class func saveImage(imageURL: String, image: UIImage) -> Void {
        mem.imageCache.setObject(image, forKey: imageURL)
    }
    
    //存储图片到文件系统中
    class func saveImageToFile(imageURL: String, image: UIImage) {
        mem.imageCache.setObject(image, forKey: imageURL)
        let fileExtension = imageURL.pathExtension
        var md5 = MD5()
        md5.rawString = imageURL.lastPathComponent.stringByDeletingPathExtension
        FileUtils.saveImage(image, withFileName: md5.checksum, ofType: fileExtension)
    }
    
    //从存储中获取图片；如获取不到，从文件系统中读取；如没有，则从网络下载后保存到文件系统，并返回图片
    class func getImageFromFile(imageURL: String, successHandler:(String, UIImage) -> Void) {
        if (imageURL == "") {
            return
        }

        if let img = mem.imageCache.objectForKey(imageURL) as? UIImage {
            successHandler(imageURL, img)
        } else {
            let fileExtension = imageURL.pathExtension
            var md5 = MD5()
            md5.rawString = imageURL.lastPathComponent.stringByDeletingPathExtension
            
            if let a = FileUtils.loadImage(md5.checksum, ofType: fileExtension) {
                saveImage(imageURL, image: a)
                successHandler(imageURL, a)
            } else {
                request(Method.GET, imageURL).validate(contentType: ["image/*"]).response({ (_request, _response, image, error) -> Void in
                    if (error == nil && image != nil) {
                        let img2 = UIImage(data: image as! NSData)
                        self.saveImageToFile(imageURL, image: img2!)
                        
                        successHandler(imageURL, img2!)
                    }
                })
            }
        }
    }
    
    //读取配置数据
    class func load() {
        var userDefault = NSUserDefaults.standardUserDefaults()
        if let a = userDefault.stringForKey(varNames.loginName) {
            mem.loginName = a
        }
        if let a = userDefault.stringForKey(varNames.password) {
            mem.password = a
        }
        if let a = Optional(userDefault.boolForKey(varNames.loginStatus)) {
            mem.loginStatus = a
        }
        if let a = Optional(userDefault.boolForKey(varNames.isCellularNet)) {
            mem.isCellularNet = a
        }
    }
}